import {createStore} from 'vuex'
import {getInfo, login, logout} from '~/api/manager.js'
import {removeToken, setToken} from "~/composables/auth.js";
import {useRouter} from "vue-router";
import {notify} from "~/composables/utils.js";
const router = useRouter()
// 创建一个新的 store 实例
const store = createStore({
    state() {
        return {
            // 用户信息
            user: {}
        }
    },
    mutations: {
        SET_USERINFO(state, user) {
            state.user = user
        }
    },
    actions: {
        // 退出登录
        logout({commit}) {
        //     清除token
            removeToken()
        //     清除vuex
            commit('SET_USERINFO', {})
        },
        // 登录
        login({commit}, { username, password }) {
            return new Promise((resolve, reject) => {
                login(username, password).then(res => {
                    setToken(res.token)
                    resolve(res)
                }).catch(err => reject(err))
            })
        },
        // 获取当前登录用户信息
        getInfo({commit}) {
            return new Promise((resolve, reject) => {
                getInfo().then(res => {
                    commit('SET_USERINFO', res)
                    resolve(res)
                }).catch(err => reject(err))
            })
        }
    }
})
export default store